# coding: utf8

import os
import sys
import codecs
import chardet

VERSION = 'v24.02.20'
DESC = u'******************************************************************\n' \
       u'* 使用说明: 将当前目录下所有*.c, *.h文件的编码格式转换为指定格式 *\n' \
       u'* 支持格式: utf-8, GB2312                                        *\n' \
       u'* 输入选择; 1 utf-8; 2 GB2312; 其它退出                          *\n' \
       u'******************************************************************'

def file_convert(filename, totype='utf-8'):
    try:
        with open(filename, 'rb') as f:
            dd = f.read()
            codeType = chardet.detect(dd)['encoding']

        if codeType == totype:
            print("文件: %s, 当前格式:%s, 无需转换" % (filename, codeType))
            return

        print("文件; %s, 当前格式:%s, 转换为:%s" % (filename, codeType, totype))

        with codecs.open(filename, 'rb', codeType) as fr:
            dd = fr.read()
        with codecs.open(filename, 'wb') as fw:
            fw.write(dd.encode(totype, errors="ignore"))
    except Exception as e:
        print("\n##转换失败: %s\n" % e)


def dir_convert(dir_path='.', totype='utf-8'):
    if not os.path.exists(dir_path):
        print('文件夹不存在')
        return
    for path, dir, filenames in os.walk(dir_path):
        for name in filenames:
            file_path = os.path.join(path, name)
            if file_path.endswith('.c') or file_path.endswith('.h') or file_path.endswith('.C') or file_path.endswith('.H'):
                file_convert(file_path, totype)

if __name__ == "__main__":
    argv = sys.argv
    dir,name = os.path.split(argv[0])

    print(u"            文件编码转换 " + VERSION + " by python")
    print(DESC)
    print(u"当前目录 " + dir)

    str = ''
    data = input(u"请输入选择: ")
    if data == '1':
        str = 'utf-8'
    elif data == '2':
        str = 'GB2312'

    if str != '':
        print(u'选择格式:%s, 开始转换...' % str)
        dir_convert(dir, str)
        print(u"转换完成...\n")

    input(u"按任意键退出...")
    pass